﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
    ViewData["Title"] = "用户管理";
}
@Html.AntiForgeryToken()
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.all.js"></script>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.mobile.css" rel="stylesheet" />
</head>
<body>
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-header">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <h2>用户管理</h2>
                    </div>
                    
                </div>
            </div>
            <div class="layui-card-body">
                <!-- 搜索栏 -->
                <form class="layui-form layui-form-pane" lay-filter="searchForm">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">用户名</label>
                            <div class="layui-input-inline">
                                <input type="text" name="Username" placeholder="请输入用户名" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">昵称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="UserNickname" placeholder="请输入昵称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn" lay-submit lay-filter="searchBtn">
                                <i class="layui-icon">&#xe615;</i> 搜索
                            </button>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                </form>

                <!-- 工具栏 -->
                <div class="layui-btn-container" style="margin-bottom: 10px;">
                    <button class="layui-btn layui-btn-normal" id="btnAdd">
                        <i class="layui-icon">&#xe654;</i> 新增用户
                    </button>
                </div>

                <!-- 数据表格 -->
                <table id="userTable" lay-filter="userTable"></table>
            </div>
        </div>
    </div>

    <!-- 表格操作列模板 -->
    <script type="text/html" id="tableBar">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="assignRole">分配角色</a>
    </script>

    <!-- 新增/编辑用户表单 -->
    <script type="text/html" id="userForm">
        <form class="layui-form" style="padding: 20px;" lay-filter="userForm">
            @Html.AntiForgeryToken()
            <input type="hidden" name="id">
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">昵称</label>
                <div class="layui-input-block">
                    <input type="text" name="userNickname" required lay-verify="required" placeholder="请输入昵称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="submitForm">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </script>

    <style>
        /* 优化分页布局 */
        .layui-table-view {
            margin-bottom: 60px;
            width: 100% !important;
        }

        .layui-table-page {
            position: static !important;
            margin: 0 auto;
            text-align: center;
            width: 100% !important;
            padding: 7px 0 !important;
            height: auto !important;
            line-height: 30px !important;
        }

        .layui-laypage {
            height: 30px !important;
            line-height: 30px !important;
        }

        .layui-laypage a,
        .layui-laypage span,
        .layui-laypage input,
        .layui-laypage button {
            height: 30px !important;
            line-height: 30px !important;
        }

        .layui-laypage input {
            height: 28px !important;
        }

        .layui-card-body {
            overflow: visible !important;
            height: auto !important;
            width: 100% !important;
        }

        .layui-table {
            width: 100% !important;
        }

        /* 让分页下拉框完整显示 */
        .layui-laypage-limits {
            min-width: 120px !important;
            max-width: none !important;
            display: inline-block !important;
            vertical-align: middle !important;
            margin: 0 !important;
            padding: 0 !important;
        }

        .layui-laypage-limits select {
            width: auto !important;
            min-width: 120px !important;
            padding-right: 25px !important;
            max-width: none !important;
            height: 30px !important;
            line-height: 30px !important;
            vertical-align: middle !important;
        }

        body {
            padding: 15px;
            background-color: #f2f2f2;
        }

        .layui-fluid {
            padding: 15px;
        }

        .layui-card {
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }

        /* 优化分页按钮的垂直对齐 */
        .layui-laypage > * {
            vertical-align: middle !important;
        }
    </style>

    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;

            // 初始化表格
            table.render({
                elem: '#userTable',
                url: '/RBAC/ShowUser',
                page: true,
                limits: [10, 20, 30, 40, 50],
                limit: 10,
                cols: [[
                    {field: 'id', title: 'ID', width: 80, sort: true},
                    {field: 'username', title: '用户名', width: 120},
                    {field: 'userNickname', title: '昵称', width: 120},
                    {title: '操作', toolbar: '#tableBar', width: 250, fixed: 'right'}
                ]],
                response: {
                    statusCode: 0
                },
                parseData: function(res) {
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.count,
                        "data": res.data
                    };
                },
                error: function(xhr, status, error) {
                    console.error('表格加载失败:', error);
                    layer.msg('数据加载失败，请刷新页面重试', {icon: 2});
                }
            });

            // 搜索按钮点击事件
            form.on('submit(searchBtn)', function(data){
                table.reload('userTable', {
                    where: data.field
                });
                return false;
            });

            // 新增按钮点击事件
            $('#btnAdd').on('click', function(){
                openUserForm();
            });

            // 表格工具条事件
            table.on('tool(userTable)', function(obj){
                var data = obj.data;
                if(obj.event === 'del'){
                    layer.confirm('确定删除此用户？', {
                        title: '删除确认',
                        btn: ['确定','取消'],
                        icon: 3
                    }, function(index){
                        var loadIndex = layer.load(2);
                        $.ajax({
                            url: '/RBAC/DeleteUser',
                            type: 'POST',
                            data: { userId: data.id },
                            traditional: true,
                            headers: {
                                'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                            },
                            success: function(res){
                                layer.close(loadIndex);
                                if(res.success){
                                    layer.msg('删除成功', {icon: 1});
                                    table.reload('userTable');
                                } else {
                                    layer.msg(res.message || '删除失败', {icon: 2});
                                }
                            },
                            error: function(xhr, status, error) {
                                layer.close(loadIndex);
                                console.error('删除失败:', error);
                                layer.msg('删除失败: ' + (xhr.responseJSON?.message || error), {icon: 2});
                            }
                        });
                        layer.close(index);
                    });
                } else if(obj.event === 'edit'){
                    openUserForm(data);
                } else if(obj.event === 'assignRole') {
                    // 打开分配角色弹窗
                    $.ajax({
                        url: '/RBAC/GetUserRoles',
                        type: 'GET',
                        data: { userId: data.id },
                        success: function(res) {
                            if (res.success) {
                                var roles = res.data;
                                var html = '<form class="layui-form" id="assignRoleForm" lay-filter="assignRoleForm" style="padding: 20px;">';
                                
                                // 添加隐藏的用户ID字段
                                html += `<input type="hidden" name="userId" value="${data.id}">`;
                                
                                // 添加角色复选框
                                roles.forEach(function(role) {
                                    html += `
                                        <div class="layui-form-item" style="margin-bottom: 5px;">
                                            <label class="layui-form-label" style="width: auto; padding-left: 0; padding-right: 10px;">
                                                <input type="checkbox" lay-filter="roleCheckbox" name="roleId_${role.id}" value="${role.id}" 
                                                       lay-skin="primary" 
                                                       ${role.isChecked ? 'checked' : ''}>
                                                <span style="padding-left: 5px;">${role.rolename}</span>
                                            </label>
                                        </div>
                                    `;
                                });

                                // 添加按钮
                                html += `
                                    <div class="layui-form-item" style="margin-top: 20px;">
                                        <div class="layui-input-block" style="margin-left: 0; text-align: center;">
                                            <button type="button" class="layui-btn" id="submitAssignRoleBtn">保存</button>
                                            <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                                        </div>
                                    </div>
                                </form>`;

                                // 先移除可能存在的旧表单
                                layer.closeAll();
                                
                                // 打开弹窗
                                layer.open({
                                    type: 1,
                                    title: '分配角色',
                                    area: ['400px', 'auto'],
                                    content: html,
                                    success: function(layero, index) {
                                        // 重新渲染表单
                                        form.render();
                                        
                                        // 解绑之前的事件
                                        $(document).off('click', '#submitAssignRoleBtn');
                                        
                                        // 绑定新的点击事件
                                        $(document).on('click', '#submitAssignRoleBtn', function() {
                                            var selectedRoleIds = [];
                                            
                                            // 获取所有选中的复选框
                                            layero.find('input[type="checkbox"]').each(function() {
                                                if ($(this).next().hasClass('layui-form-checked')) {
                                                    selectedRoleIds.push(parseInt($(this).val()));
                                                }
                                            });

                                            console.log('选中的角色IDs:', selectedRoleIds);

                                            if (selectedRoleIds.length === 0) {
                                                layer.msg('请至少选择一个角色', {icon: 2});
                                                return false;
                                            }

                                            var userId = parseInt($('#assignRoleForm input[name="userId"]').val());
                                            var requestData = {
                                                userId: userId,
                                                roleIds: selectedRoleIds
                                            };

                                            console.log('发送的数据:', requestData);

                                            // 发送请求
                                            $.ajax({
                                                url: '/RBAC/AssignUserRoles',
                                                type: 'POST',
                                                contentType: 'application/json',
                                                data: JSON.stringify(requestData),
                                                headers: {
                                                    'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                                                },
                                                success: function(res) {
                                                    console.log('角色分配响应:', res);
                                                    if (res.success) {
                                                        layer.msg('角色分配成功', {icon: 1});
                                                        layer.closeAll();
                                                        table.reload('userTable');
                                                    } else {
                                                        console.error('角色分配失败:', res.message);
                                                        layer.msg(res.message || '角色分配失败', {icon: 2});
                                                    }
                                                },
                                                error: function(xhr) {
                                                    console.error('角色分配请求失败:', xhr);
                                                    layer.msg(xhr.responseJSON?.message || '角色分配失败', {icon: 2});
                                                }
                                            });
                                        });
                                    },
                                    end: function() {
                                        // 弹窗关闭时解绑事件
                                        $(document).off('click', '#submitAssignRoleBtn');
                                    }
                                });
                            } else {
                                layer.msg(res.message || '获取角色列表失败', {icon: 2});
                            }
                        },
                        error: function(xhr) {
                            layer.msg(xhr.responseJSON?.message || '获取角色列表失败', {icon: 2});
                        }
                    });
                }
            });

            // 打开用户表单
            function openUserForm(userData) {
                var title = userData ? '编辑用户' : '新增用户';
                
                layer.open({
                    type: 1,
                    title: title,
                    area: ['500px', '400px'],
                    content: $('#userForm').html(),
                    success: function(layero, index){
                        form.render();
                        
                        // 如果是编辑，设置表单数据
                        if(userData) {
                            form.val('userForm', {
                                'id': userData.id,
                                'username': userData.username,
                                'userNickname': userData.userNickname
                            });
                            
                            // 编辑模式下设置
                            $('input[name="username"]').attr('required', false);
                            $('input[name="password"]').attr('required', false);
                            $('input[name="password"]').attr('lay-verify', '');
                            $('.password-field').hide(); // 可以选择隐藏密码字段
                        } else {
                            // 新增模式下的默认值
                            form.val('userForm', {
                                'id': 0,
                                'username': '',
                                'password': '',
                                'userNickname': ''
                            });
                        }
                    }
                });
            }

            // 表单提交事件
            form.on('submit(submitForm)', function(data){
                console.log("表单数据:", data.field);
                
                var isEdit = data.field.id && data.field.id != '0';
                var url = isEdit ? '/RBAC/UpdateUser' : '/RBAC/AddUser';
                var method = isEdit ? 'PUT' : 'POST';

                // 构建提交数据
                var submitData = {
                    id: parseInt(data.field.id) || 0,
                    username: data.field.username,
                    userNickname: data.field.userNickname
                };

                // 只在新增时或密码不为空时添加密码字段
                if (!isEdit || data.field.password) {
                    submitData.password = data.field.password;
                }

                // 获取防伪token
                var token = $('input[name="__RequestVerificationToken"]').val();

                console.log("提交的数据:", JSON.stringify(submitData));
                
                $.ajax({
                    url: url,
                    type: method,
                    contentType: 'application/json',
                    data: JSON.stringify(submitData),
                    headers: { 'RequestVerificationToken': token },
                    success: function(res){
                        if(res.success){
                            layer.closeAll();
                            layer.msg(isEdit ? '修改成功' : '添加成功');
                            table.reload('userTable');
                        } else {
                            layer.msg(res.message || '操作失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('操作失败:', error);
                        layer.msg('操作失败: ' + (xhr.responseJSON?.message || error), {icon: 2});
                    }
                });
                return false;
            });
        });
    </script>
</body>
</html>
